<?php
/**
 * Created by PhpStorm.
 * User: Aliaksei Lazerka
 * Date: 10/16/14
 * Time: 10:57 PM
 */

include_once("../lib/nymph/NymphFramework.php");
include_once("../ActionResolver.php");
include_once("../RequestContext.php");
include_once("SQLParser.php");
include_once("../messages/conf.php");
include_once("DBTypes.php");

use exception\IException;

global $requestContext;
$requestContext = new \controller\RequestContext();

/**
 * @param IException $exception
 */
function handleException($exception)
{
  global $requestContext;
  $requestContext->addException($exception);
  include_once("../includes/error.php");
  exit();
}

set_exception_handler('handleException');

/**
 * Is used for setting variables in the request context
 * @param $key
 * @param $value
 */
function throwError($key, $value)
{
  global $requestContext;
  $requestContext->addError($key, $value);
  include_once(dirname(__FILE__) . "../includes/error.php");
  exit();
}

/**
 * @return array
 */
function getErrors()
{
  global $requestContext;
  return $requestContext->getErrors();
}

/**
 * @param string $key
 * @param string $value
 */
function addError($key, $value)
{
  global $requestContext;
  $requestContext->addError($key, $value);
}

/**
 * @return IException[]
 */
function getExceptions()
{
  global $requestContext;
  return $requestContext->getExceptions();
}

/**
 * @return bool
 */
function hasErrors()
{
  global $requestContext;
  return $requestContext->hasErrors();
}

ob_start();

include_once("../filter/encoding.php");

$action = ActionResolver::getActionFromUrl();

if (!$action) {
  ob_end_clean();
  throwError("Страница не найдена !", "Внимание, страница с именем \"" . ActionResolver::getActionNameFromUrl() . "\" не найдена !");
}

include_once($action . ".php");

if (!hasErrors()) {
  ob_end_flush();
} else {
  ob_end_clean();
  include_once("../includes/error.php");
}